<template>
  <div class="progress-output-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="search-container">
        <div class="search-item">
          <el-date-picker
            v-model="searchDate"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <el-button type="primary" @click="handleSearch">
            <i class="el-icon-search"></i>
          </el-button>
          <el-button type="primary" @click="handleRefresh">
            <i class="el-icon-refresh"></i>
          </el-button>
          <transition name="fade" appear>
            <div class="total-progress" v-show="!tableVisible">
              总进度：<span>{{ this.statis.completeRate }}</span>
            </div>
          </transition>
        </div>
        <div class="search-item">
          <el-button type="primary" @click="handleChange">{{ btnText }}</el-button>
          <transition name="fade" appear>
            <el-button v-if="hasTabAdd" type="primary" v-show="tableVisible" @click="handleAdd">新建</el-button>
          </transition>
        </div>
      </div>
      <transition name="fade" appear>
        <div class="table-container" v-show="tableVisible">
          <el-table
            class="table-content"
            v-loading="tableLoading"
            show-summary
            :summary-method="getSummaries"
            element-loading-custom-class="custom-load"
            row-key="id"
            :data="tableData">
            <el-table-column label="序号" type="index" width="80"></el-table-column>
            <el-table-column label="时间" prop="monthOut"></el-table-column>
            <el-table-column label="计划费用(PV)" prop="planOut"></el-table-column>
            <el-table-column label="赢得值(EV)" prop="actualOut"></el-table-column>
            <el-table-column label="实际成本(AC)" prop="actualCost"></el-table-column>
            <el-table-column label="完成率(%)" prop="completeRate"></el-table-column>
            <el-table-column label="费用偏差(CV)" prop="cv"></el-table-column>
            <el-table-column label="进度偏差(SV)" prop="sv"></el-table-column>
            <el-table-column label="费用绩效指数(CPI)" prop="cpi"></el-table-column>
            <el-table-column label="进度绩效指数(SPI)" prop="spi"></el-table-column>
            <el-table-column label="状态" prop="status"></el-table-column>
            <el-table-column label="备注" prop="remark"></el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <span style="display: none;"></span>
                <span v-if="hasTableEdit" class="btn" @click="handleEdit(scope.row)">编辑</span>
                <span v-if="hasTableDel" class="btn" @click="handleDelete(scope.row)">删除</span>
              </template>
            </el-table-column>
            <div class="empty-content" slot="empty">
              <i class="iconfont iconwushuju"></i>
              <p>暂无数据</p>
            </div>
          </el-table>
          <el-pagination
            v-if="total > 10"
            :page-size="pageSize"
            :current-page="pageNo"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 50]"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </transition>
      <div class="echarts-container ">
        <echarts-base :options="echartsOptions"></echarts-base>
      </div>
    </main>
    <add-progress-out
      :visible="visible"
      :loading="loading"
      :formData="currentData"
      @cancel="handleCancel"
      @submit="handleSave">
    </add-progress-out>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import echartsBase from '@/components/echarts/base';
import addProgressOut from '@/components/project/progress/addProgressOut';

export default {
  data() {
    return {
      breadcrumbData: [
        { name: '进度管理' },
        { name: '进度产值' }
      ],
      checkId: '',
      searchDate: [],
      hasSearch: false,
      tableLoading: false,
      tableData: [],
      statis: {},
      total: 0,
      pageSize: 10,
      pageNo: 1,
      currentData: {},
      visible: false,
      loading: false,
      tableVisible: true
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    btnText() {
      return this.tableVisible ? '图表模式' : '列表模式';
    },
    echartsData() {
      const result = {
        legend: ['计划产值', '实际产值'],
        xAxisData: [],
        series: []
      };
      const setConfig = (name, colorList = [], list = []) => {
        return {
          name,
          type: 'bar',
          barGap: 0,
          data: list,
          label: {
            show: true,
            position: 'top',
            color: '#fff'
          },
          itemStyle: {
            color: new this.$echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                {
                  offset: 0,
                  color: colorList[0] || '#e0858c'
                },
                {
                  offset: 1,
                  color: colorList[1] || '#a2c377'
                }
              ]
            )
          }
        };
      };
      const planData = [];
      const actualData = [];
      this.tableData.forEach(item => {
        const { actualOut, planOut, monthOut } = item;
        // 设置横轴
        result.xAxisData.push(monthOut);
        // 设置数据
        planData.push(planOut);
        actualData.push(actualOut);
      });
      result.series.push(setConfig(result.legend[0], [], planData));
      result.series.push(setConfig(
        result.legend[1],
        ['#213e92', '#b37dfb'],
        actualData
      ));
      return result;
    },
    // 产值图表配置
    echartsOptions() {
      return {
        textStyle: {
          color: '#fff'
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            minValueSpan: 5,
            zoomLock: false
          }
        ],
        legend: {
          data: this.echartsData.legend,
          // right: 100,
          textStyle: {
            color: '#fff'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.echartsData.xAxisData,
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          // 刻度
          axisTick: {
            show: false
          }
        },
        series: this.echartsData.series
      };
    }
  },
  created() {
    this.getTableData();
  },
  components: {
    Breadcrumb,
    addProgressOut,
    echartsBase
  },
  methods: {
    /**
     * 获取列表数据
     */
    async getTableData() {
      const params = {
        projectId: this.projectId,
        pageNum: this.pageNo,
        pageSize: this.pageSize
      };
      if (this.hasSearch) {
        params.startTime = this.searchDate[0];
        params.endTime = this.searchDate[1];
      }
      this.tableLoading = true;
      const { success, data: { data }} = await this.$Model.getProgressOut(params);
      this.tableLoading = false;
      if (success && data) {
        const { pageInfo, statis } = data;
        if (pageInfo) {
          this.tableData = pageInfo.list || [];
          this.total = pageInfo.total || 0;
        }
        this.statis = statis || {};
      }
    },
    // 合计设置
    getSummaries(param) {
      const { columns } = param;
      const sums = [];
      columns.forEach((column, index) => {
        switch (index) {
          case 0:
            sums[index] = '合计';
            return;
          case 1:
            sums[index] = `${this.statis.minMonth || ''} - ${this.statis.maxMonth || ''}`;
            return;
          case 2:
            sums[index] = this.statis.planOut;
            return;
          case 3:
            sums[index] = this.statis.actualOut;
            return;
          case 5:
            sums[index] = this.statis.completeRate;
            return;
          default:
            sums[index] = '';
            break;
        }
      });

      return sums;
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getTableData();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getTableData();
    },
    clear() {
      this.pageNo = 1;
      this.pageSize = 10;
      this.total = 0;
      this.tableLoading = false;
      this.tableData = [];
    },
    // 搜索
    handleSearch() {
      this.clear();
      this.hasSearch = this.searchDate && this.searchDate.length;
      this.getTableData();
    },
    // 重置
    handleRefresh() {
      this.clear();
      this.hasSearch = false;
      this.searchDate = [];
      this.getTableData();
    },
    // 新建
    handleAdd() {
      this.currentData = {};
      this.visible = true;
    },
    // 编辑
    handleEdit(row) {
      this.currentData = { ...row };
      this.visible = true;
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.deleteProgressOut({
          ids: row.id
        });
        if (success) {
          this.$message.success('删除成功');
          this.clear();
          this.getTableData();
        }
      });
    },
    handleCancel() {
      this.visible = false;
      this.loading = false;
    },
    // 保存设置
    async handleSave(data) {
      const params = {
        projectId: this.projectId,
        ...data
      };
      this.loading = true;
      const { success } = this.type === 'add'
        ? await this.$Model.addProgressOut(params)
        : await this.$Model.addProgressOut({
          ...params,
          id: this.currentData.id
        });
      this.loading = false;
      if (success) {
        this.$message.success('保存成功');
        this.getTableData();
        this.visible = false;
      }
    },
    // 切换图表
    handleChange() {
      this.tableVisible = !this.tableVisible;
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';
  .progress-output-page {
    width: 100%;
    height: 100%;
    background-color: $mainBg;
    overflow: hidden;
    main {
      width: 100%;
      height: calc(100% - 40px);
      padding: 0 20px;
      .search-container {
        width: 100%;
        height: 50px;
        margin: 20px 0;
        display: flex;
        justify-content: space-between;
        .search-item {
          height: 100%;
          float: left;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-right: 20px;
          .el-button {
            margin-left: 10px;
          }
          .total-progress {
            margin-left: 40px;
            font-size: 20px;
            font-weight: bold;
            span {
              font-family: font-lcd;
              font-size: 36px;
            }
          }
        }
      }
      .table-container {
        width: 100%;
        height: calc(100% - 80px);
        background-color: $mainBg;
        border-radius: 10px;
        position: relative;
        .table-content {
          height: calc(100% - 50px);
          /deep/ .el-table__body-wrapper {
            padding-bottom: 46px;
            max-height: calc(100% - 100px);
            overflow-y: auto;
            .btn {
              padding: 0 5px;
              cursor: pointer;
              color: $mainColor;
            }
            .el-icon-download {
              cursor: pointer;
              font-size: 16px;
            }
          }
          /deep/ .el-table__footer-wrapper {
            td {
              font-weight: bold;
            }
          }
        }
      }
      .echarts-container {
        width: 100%;
        height: 580px;
        position: relative;
      }
    }
    .fade-enter-active, .fade-leave-active {
      transition: opacity .3s;
    }
    .fade-enter, .fade-leave-to {
      opacity: 0;
    }
  }
</style>
